package cc.higou.service;

import cc.higou.core.dao.BrandMapper;
import cc.higou.core.pojo.Brand;
import cc.higou.core.tools.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 说明：
 * 查询品牌的的业务实现类
 *
 * @author:dongxing
 * @time:--
 */
@Service("brandService")
public class BrandServiceImpl implements BrandService {
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private Jedis jedis;

    @Override
    public PageHelper.Page<Brand> findByExample(Integer pageNum, Integer pageSize, Brand brand) {

        //分页
        PageHelper.startPage(pageNum, pageSize);
        brandMapper.findByExample(brand);
        PageHelper.Page endPage = PageHelper.endPage();

        return endPage;
    }

    @Override
    public Brand findById(Long id) {
        return brandMapper.findById(id);
    }

    @Override
    public void update(Brand brand) {

        //增删改的时候，将品牌的id和名称放入到redis中
        Long id = brand.getId();
        String name = brand.getName();
        jedis.hset("brand", String.valueOf(id), name);
        brandMapper.update(brand);
    }

    @Override
    public void add(Brand brand) {
        brandMapper.add(brand);
        //将品牌的id和名称放入redis中
        Long id = brand.getId();
        String name = brand.getName();
        jedis.hset("brand", String.valueOf(id), name);
    }

    @Override
    public void deleteByids(String ids) {
        ids.replaceAll(" ", "");
        brandMapper.deleteByids(ids);
        //将对应的redis中的数据删除
        String[] split = ids.split(",");
        for (String id : split) {
            jedis.hdel("brand", id);
        }

    }

    @Override
    public List<Brand> findAll() {
        return brandMapper.findAll();
    }

    @Override
    public List<Brand> findAllFromRedis() {
        List<Brand> list = new ArrayList<>();
        Map<String, String> map = jedis.hgetAll("brand");
        for (Map.Entry<String, String> entry :map.entrySet()) {
            Brand brand = new Brand();
            brand.setId(Long.parseLong(entry.getKey()));
            brand.setName(entry.getValue());
            list.add(brand);
        }

        return list;
    }
}
